const http = require("http");
const url = require("url");
const https = require("https");

const server = http.createServer(function (req, res) {
  res.writeHead(200, {
    "Content-Type": "application/json;charset=utf-8",
    "Access-Control-Allow-Credentials": true,
    "Access-Control-Allow-Origin": "*", //可以是*，也可以是跨域的地址
  });
});

server.listen(3001, () => {
  console.log("http://127.0.0.1:3001");
});

// 监听用户请求
server.on("request", (req, res) => {
  console.log(req.url);
  var params = url.parse(req.url, true).query;
  const address = params.add;

  (address.includes("https") ? https : http)
    .get(
      `${address}?ac=${params.ac}${params.t ? `&t=${params.t}` : ""}${params.pg ? `&pg=${params.pg}` : ""}${
        params.wd ? `&wd=${params.wd}` : ""
      }${params.h ? `&h=${params.h}` : ""}${params.ids ? `&ids=${params.ids}` : ""}`,
      (resp) => {
        let data = "";
        resp.on("data", function (chunk) {
          data += chunk;
        });
        resp.on("end", () => {
          res.end(data);
        });
        resp.on("error", (err) => {
          console.log(err.message);
          res.end(`${err}`);
        });
      }
    )
    .on("error", (e) => console.log("error", e));
});
